package com.woniuxy.intellihome.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.intellihome.entity.Order;
import com.woniuxy.intellihome.entity.Orderitem;
import com.woniuxy.intellihome.entity.ResponseEntity;
import com.woniuxy.intellihome.entity.ResponseState;
import com.woniuxy.intellihome.service.OrderService;
import com.woniuxy.intellihome.service.OrderitemService;
import com.woniuxy.intellihome.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 * @author pengZhihong
 * @since 2021-08-14
 * 1、完成后台订单筛选、查询、分页、删除、修改功能，实现基本功能的搭建
 *
 *
 * @author pengZhihong
 * @since 2021-08-12
 * 1、更新了Order订单的分页查询功能，目前能完成基本的分页实现，后续有待完善
 */
@RestController("/admin/order")
@RequestMapping("/admin/order")
public class OrderController {


    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderitemService orderitemService;
    @Autowired
    private UserService userService;


    /**
     * 实现根据发送筛选条件对数据库内容进行筛选查询，并将信息通过JSON返回
     * @param current 选择页码
     * @param order 筛选条件，null则代表所有
     * @param result
     * @return JSON语句
     */
    @PostMapping("/list")
    public ResponseEntity<List<Order>> list(@RequestParam(value = "current",defaultValue = "1")Integer current,
                                            @RequestParam(value = "pageSize",defaultValue = "5")Integer pageSize,
                                            @RequestBody Order order, BindingResult result){
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();

        if(order == null){
            order = new Order();
        }
        //设置Order查询条件
        //订单编号、user用户、下单时间、收货人、订单状态
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (order.getOrderNum() != null && order.getOrderNum().trim().length() != 0) {
            queryWrapper.like("order_num", order.getOrderNum());
        }
        if (order.getStartOrderTime() != null && order.getStartOrderTime().trim().length() != 0) {
            queryWrapper.ge("order_time", order.getStartOrderTime());
        }
        if (order.getEndOrderTime() != null && order.getEndOrderTime().trim().length() != 0) {
            queryWrapper.le("order_time", order.getEndOrderTime());
        }
        if (order.getAccept() != null && order.getAccept().trim().length() != 0) {
            queryWrapper.eq("accept", order.getAccept());
        }
        if (order.getStatus() != null && order.getStatus().trim().length() != 0) {
            queryWrapper.eq("status", order.getStatus());
        }
        queryWrapper.gt("status",0);

        //检查是否存在错误
        if(result.hasFieldErrors()){
            //不存在返回无效提示
            Map<String,String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e ->{
                msgs.put(e.getField(),e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        }else{
            //查询数据中所有科目分页信息，并返回JSON语句
            Page<Order> page = new Page<>(current,pageSize);
            //返回JSON数据
            page = orderService.page(page,queryWrapper);

            //获取order数组,根据id查询orderitems并存入
            List<Order> orders1 = page.getRecords();
            //类型转换，将getRecords获得的对象类型由AbstractList转换为Arraylist，防止下面的add方法报错
            List<Order> orders = new ArrayList<>(orders1);
            //将查询条件存入第一个
            orders.add(0,order);
            for (Order value : orders) {
                List<Orderitem> orderitems = orderitemService.getByOrderId(value.getId());
                value.setOrderitems(orderitems);
            }
            page.setRecords(orders);

            responseEntity.setCode(ResponseState.SUCCESS);
            responseEntity.setMsg("查询成功");
            responseEntity.setData(page);
        }

        return responseEntity;
    }

    /**
     * 1、根据前台数据变化修改订单(仅修改订单，订单明细未变动)
     * 2、对删除订单功能，实现订单status状态的修改，使order被动隐藏
     * @param order 前台返回order信息
     * @param result
     * @return JSON语句
     */
    @PostMapping("/update")
    public ResponseEntity update(@RequestBody Order order, BindingResult result){
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();
        //检查是否存在错误
        if(result.hasFieldErrors()){
            //不存在返回无效提示
            Map<String,String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e ->{
                msgs.put(e.getField(),e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        }else{
            orderService.saveOrUpdate(order);
            //返回修改结果
            responseEntity.setCode(ResponseState.SUCCESS);
            responseEntity.setMsg("成功");
            responseEntity.setData(order);
            return responseEntity;
        }
        return responseEntity;
    }


}

